from pynput import keyboard
import queue
import time
import threading

class MyThread(threading.Thread):
    def __init__(self, name, queue):
        super().__init__()
        self.name = name
        self.queue = queue

    def run(self):
        print('Thread: {} start at {}'.format(self.name, time.ctime(time.time())))
        while True:
            # 等待event.set()后，才能往下执行
            newKey = self.queue.get(True)
            print('Thread: {} comsume {} time{}'.format(self.name, newKey, time.ctime(time.time())))


def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
        keyQueue.put(key.char)
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False


keyQueue = queue.Queue()

threads = []
[threads.append(MyThread(str(i), keyQueue)) for i in range(1,2)]

# 启动所有线程
[t.start() for t in threads]


# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()